package com.awspaas.user.apps.cpq.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;

public class CPQ_GetRecordTransportNumberWeb {

	public String getRecordTransportNumber(UserContext userContext, String bindId, String cs, String datas) {
		try {
			Map<String, JSONObject> pMap = new HashMap<String, JSONObject>();
			Map<String, String> nameMap = new HashMap<String, String>();
			Map<String, String> noMap = new HashMap<>();
			List<BO> ps=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_RECORD_PARAMETERS").bindId(bindId).list();
			List<BO> bos = SDK.getBOAPI().query("BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR").bindId(bindId).list();
			if(ps.size()>0) {
				for (int i = 0; i < ps.size(); i++) {
					BO json = ps.get(i);
					String bh =  json.getString("PARMENTIER_NO");
					String value =  json.getString("PARMENTIER_VALUE");
					String name =json.getString("PARMENTIER_NAME");
					String dw = json.getString("DW");
					JSONObject jsonObject=new JSONObject();
					//判断value是否为数据
					if( NumberUtils.isCreatable(value)) {
						jsonObject.put("type", "1");//值为1者表示value为数值
					}else {
						jsonObject.put("type", "0");//值为0者表示value为字符串
					}
					jsonObject.put("value", value);
					pMap.put(bh, jsonObject);
					nameMap.put(bh, name);
					int num = i + 1;
					noMap.put(bh, "B$" + num);
				}
				System.out.println("pMap:"+pMap.toString());			
			}	
			// 获取模块编码信息
			Map<String, BO> idMap = new HashMap<>();
			String bms = "";
			for (BO json : bos) {
			//	JSONObject json = (JSONObject) string;
				String bm = json.getString("BM");
				if (bms.isEmpty()) {
					bms = "'" + bm + "'";
				} else {
					bms += ",'" + bm + "'";
				}
				String id = json.getString("ID");
				idMap.put(id, json);
			}
			String sql = "select  * from  BO_EU_CPQ_TRANSPORT where   BM in (" + bms + ")";
			List<RowMap> maps = DBSql.getMaps(sql);
			Map<String, RowMap> moduleMap = new HashMap<>();
			if (maps.size() > 0) {
				for (RowMap rowMap : maps) {
					String mkbm = rowMap.getString("BM");
					moduleMap.put(mkbm, rowMap);
				}
			}
			 //存放已经保存的数据
		  	Map<String, BO> boMap = new HashMap<>();
		  	for (BO bo : bos) {
		  		boMap.put(bo.getString("ID"), bo);
		  	}
		    double totalPrice=0;
		    for (String  id : idMap.keySet()) {
		    	Workbook workbook = new XSSFWorkbook();
				double price=0;
				try {	
					// 获取对应编码的数据信息；
					if (idMap.containsKey(id)) {
						BO json = idMap.get(id);
						String bm = json.getString("BM");
						// 获取模块维护台账的模块数据
						//RowMap rowMap = moduleMap.get(bm);
						String rule = json.getString("JSGS"); // 计算规则
						/**
						 * 计算工艺数量。
						 */
						if (!rule.equals("0") && !rule.isEmpty()) {
							Document document = Jsoup.parse(rule);
							  String newRule=document.text();
							Map<String, BO> materMap = new HashMap<>();
							System.out.println("模块计算规则新："+newRule);
							
							// 设置单元格值
							Sheet sheet = workbook.createSheet("Sheet1");
							for (int i = 0; i < ps.size(); i++) {
								int num = i + 1;
								Cell cellB1 = sheet.createRow(i).createCell(1);
								//JSONObject jsonObject = (JSONObject) list.get(i);
								BO jsonObject = ps.get(i);
								String bh = jsonObject.getString("PARMENTIER_NO");
								JSONObject jsonObject2=	pMap.get(bh);
								String type=jsonObject2.getString("type");
								if(type.equals("0")) {
									cellB1.setCellValue(jsonObject2.getString("value"));
									System.out.println("cellB1:"+cellB1.getStringCellValue());
								}else {
									String value=jsonObject2.getString("value");
									double  numValue=Double.parseDouble(value);		
									 cellB1.setCellValue(numValue);
									 System.out.println("cellB1:"+cellB1.getNumericCellValue());
								}
								
								
							}
							// 获取直发物质运费维护数据中数量计算公式中参数代号，如果有则将代号存放在list中
							for (String key : pMap.keySet()) {
								int num = newRule.indexOf(key);
								if (num > -1) {
									newRule = newRule.replace(key, noMap.get(key));
								}
							}
							// 计算出工艺数量和当前工艺的成本价格
							Cell cellB1 = sheet.createRow(ps.size()+1).createCell(3);
							cellB1.setCellFormula(newRule);
							// 创建公式评估器
							FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
							System.out.println("cellB1value:"+cellB1.getCellFormula());
							formulaEvaluator.evaluateFormulaCell(cellB1);
							// 获取公式计算结果
							CellValue cellValue = formulaEvaluator.evaluate(cellB1);
							System.out.println("The result of the formula is: " + cellValue.getNumberValue());
							double number = cellValue.getNumberValue();
							// 总成本价
							double MKDJ = Double.parseDouble(json.getString("YFBZ"));// 运费标准
							double MKTotalPrice = number * MKDJ;
							//price=MKTotalPrice;
							if(boMap.containsKey(id)) {
								BO mbo=	boMap.get(id);
								mbo.set("YFBZ", MKDJ);// 单价
								mbo.set("SL", number);// 数量
								mbo.set("MDSF", json.getString("MDSF"));// 目的省份
								mbo.set("ZL", json.getString("ZL"));// 分类
								mbo.set("YFJG", MKTotalPrice);// 总价
								mbo.set("MC", json.getString("MC"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码								
								System.out.println("计算后的价格："+mbo.toString());
								SDK.getBOAPI().update("BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR", mbo);
							}else {
								BO mbo=	new BO();
								mbo.set("YFBZ", MKDJ);// 单价
								mbo.set("SL", number);// 数量
								mbo.set("MDSF", json.getString("MDSF"));// 目的省份
								mbo.set("ZL", json.getString("ZL"));// 分类
								mbo.set("YFJG", MKTotalPrice);// 总价
								mbo.set("MC", json.getString("MC"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码								
								SDK.getBOAPI().create("BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR", mbo, bindId, userContext.getUID());
							}
							
						}else {
							if(boMap.containsKey(id)) {
								BO mbo=	boMap.get(id);
								mbo.set("YFBZ", json.getString("YFBZ"));// 单价
								mbo.set("SL", json.getString("SL"));// 数量
								mbo.set("MDSF", json.getString("MDSF"));// 目的省份
								mbo.set("ZL", json.getString("ZL"));// 分类
								mbo.set("YFJG", json.getString("YFJG"));// 总价								
								mbo.set("MC", json.getString("MC"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码
								
								SDK.getBOAPI().update("BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR", mbo);			
							}else {
								BO mbo=	new BO();
								mbo.set("YFBZ", json.getString("YFBZ"));// 单价
								mbo.set("SL", json.getString("SL"));// 数量
								mbo.set("MDSF", json.getString("MDSF"));// 目的省份
								mbo.set("ZL", json.getString("ZL"));// 分类
								mbo.set("YFJG", json.getString("YFJG"));// 总价
								mbo.set("MC", json.getString("MC"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码
							
								SDK.getBOAPI().create("BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR", mbo, bindId, userContext.getUID());				
							}
							
							
						}
						
					}
					
				}catch (Exception e){
					 throw  e;
				}finally {
		  			 try {
						workbook.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} 
		    }
		    ResponseObject ro = ResponseObject.newOkResponse();
			return ro.toString();
		} catch (Exception e) {
			throw e;
		}
		
	}

}
